<template>
  <div class="login-container">
    <el-card class="box-card">
      <h2 class="h-login">登录</h2>
      <el-form :model="formData"  ref="loginFormRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" autocomplete="off"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loginHandler">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: 'study6Login'
}
</script>

<script setup lang="ts">
import { reactive } from 'vue'

import { type IUserLoginInfo, apiLogin } from '@/service/study6/demo5'
import { useRouter } from 'vue-router'

const router = useRouter()

const formData: IUserLoginInfo = reactive({
  username: '',
  password: ''
})

// 执行登录
const loginHandler = async () => {
  try {
    const resData = await apiLogin(formData)

    if (resData.code !== '2000' || !resData.data) {
      throw new Error(resData.msg || '未知错误')
    }
    // 登录成功
    localStorage.setItem('token', resData.data)

    router.replace({ path: '/studemo72/user' })
  } catch (e: Error) {
    alert(e.message)
  }
}
</script>

<style scoped>
.h-login {
  text-align: center;
  margin-bottom: 30px;
}
.login-container {
  display: flex;
  justify-content: center;
  margin-top: 100px; /* 修改了这里的值，因为之前的 `˜0px` 是无效的 */
}
.box-card {
  width: 300px;
}
</style>